package logic

import (
	"context"

	"go-zero-mall/app/admin/cmd/rpc/internal/svc"
	"go-zero-mall/app/admin/cmd/rpc/pd"
	"go-zero-mall/app/admin/model"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/fx"
	"github.com/zeromicro/go-zero/core/logx"
)

type MenuTreeListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewMenuTreeListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MenuTreeListLogic {
	return &MenuTreeListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 菜单-树形菜单
func (l *MenuTreeListLogic) MenuTreeList(in *pd.Request) (*pd.UmsMenuTreeListResp, error) {
	rowBuilder := l.svcCtx.UmsMenuModel.RowBuilder()
	d, err := l.svcCtx.UmsMenuModel.FindList(l.ctx, rowBuilder)
	if err != nil {
		return nil, err
	}
	var temp []interface{}
	copier.Copy(&temp, d)
	var menus []*pd.Menu

	fx.Just(temp...).ForEach(func(item interface{}) {
		var menu pd.Menu
		copier.Copy(&menu, item)
		menus = append(menus, &menu)
	})

	var mainTree []*pd.Menu
	fx.Just(temp...).Filter(func(item interface{}) bool {
		return item.(*model.UmsMenu).Level == 0
	}).ForEach(func(item interface{}) {
		var menu pd.Menu
		copier.Copy(&menu, item)
		mainTree = append(mainTree, &menu)
	})
	for _, v := range mainTree {
		getChildrenTree(menus, v)
	}

	return &pd.UmsMenuTreeListResp{List: mainTree}, nil
}
func getChildrenTree(menus []*pd.Menu, main *pd.Menu) {
	for _, v := range menus {
		if v.ParentId == main.Id {
			main.Node = append(main.Node, v)
		}
	}
	if main.Node != nil {
		for _, v := range main.Node {
			getChildrenTree(menus, v)
		}
	}
}
